import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';// Progress 进度条样式
import { useSystemStore, useUserStore } from '@/stores'
import commonApi from '@/api/common/common'
import authApi from '@/api/common/auth'
import config from '@/config'

const modules = import.meta.glob('@/views/**/*.vue')
function _import(viewPath: string): any {
  const fullPath = `/src/views${viewPath}.vue`
  const func = modules[fullPath]
  if (!func) {
    console.log(fullPath)
  }
  //开发状态下就直接加载，生产状态就采用懒加载
  // return import.meta.env.DEV ? func() : func
  return func;
}

const layoutModules = import.meta.glob('@/components/common/layout/*/index.vue')
function _importLayout(layout: string): any {
  const fullPath = `/src/components/common/layout/${layout}/index.vue`
  // return layoutModules[fullPath]()
  return layoutModules[fullPath]
}


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/index' },
    {
      path: '/login',
      name: 'login',
      // component: _import.default('@/pages/login.vue'),
      component: _import('/login'),
      meta: {
        noAuth: true
      }
    },
    {
      path: '/qywxAuth/:path?',
      name: 'qywxAuth',
      component: _import('/qywxAuth'),
      props: true,
      meta: {
        title: '微信企业认证',
        noAuth: true
      }
    }
  ]
})
router.beforeEach(async (to, from) => {
  NProgress.start();
  const systemStore = useSystemStore()
  const userStore = useUserStore()
  //判断是否已加载配置信息
  if (systemStore.config.size == 0) {
    const res = await commonApi.getConfigList();
    systemStore.config = new Map();
    (res.data as Array<any>).forEach(item => {
      switch (item.type) {
        case "NUMBER":
          systemStore.config.set(item.key, Number(item.value));
          break;
        case "BOOL":
          systemStore.config.set(item.key, item.value == "ON" ? true : false)
          break;
        default:
          systemStore.config.set(item.key, item.value)
      }
    });
  }

  /* 判断要访问的路由是否需要权限访问 */
  if (to.meta && to.meta.noAuth) {
    return true
  }
  console.log(localStorage.getItem(config.token.accessKey))
  /* 判断是否有已登录 */
  if (localStorage.getItem(config.token.accessKey) == null) {
    return '/login'
    // if (from.path == "/login") {
    //   NProgress.done()
    // }
  }

  /* 判断是否已获取登录认证信息 */
  if (userStore.hasAuthInfo) {
    return true
  }

  // let { default: layout } = await import("../components/common/layout/" + systemStore.config.get('LAYOUT') + "/index")
  /* 获取登录认证信息 */
  const res = await authApi.getAuthInfo()
  if (res.code != 0) {
    return '/login';
  }
  const permissionMenus: Array<any> = res.data.menuPermissions;
  permissionMenus.unshift({
    id: -1,
    name: config.homePage.name,
    path: config.homePage.path,
    icon: config.homePage.icon,
    parentId: null
  })
  const menus: Array<any> = []; //树结构菜单

  const layoutRouter: any = {
    name: "layout",
    path: "",
    component: _importLayout(systemStore.config.get('LAYOUT')),
    children: [
      //空白路由，用于刷新
      {
        name: "blank",
        path: "blank",
        component: null,
        meta: null
      }
    ]
  };

  //构建完整路径及权限路径值
  function buildPermissionAndFullPath(menu: any) {
    permissionMenus.forEach((m, i) => {
      if (m.parentId == menu.id) {
        m.fullPath = menu.fullPath + '/' + m.path;
        m.permissionPath = (menu.permissionPath ? (menu.permissionPath + '.') : "") + m.path;
        buildPermissionAndFullPath(m);
      }
    })
  };
  buildPermissionAndFullPath({
    id: null,
    fullPath: "",
    permissionPath: ""
  });

  //先取出顶级菜单
  permissionMenus.forEach(item => {
    if (item.isPage) {
      layoutRouter.children.push({
        name: item.permissionPath,
        path: item.fullPath,
        component: _import(item.fullPath + ".vue"),
        meta: {
          id: item.id,
          title: item.name,
          canMultipleOpen: item.canMultipleOpen,
          isPage: item.isPage
        }
      })
    } else if (item.parentId == null) {
      menus.push(item);
    }
  })
  //构建菜单及路由
  function buildMenusAndRouters(menus: Array<any>) {
    menus.forEach(item => {
      permissionMenus.forEach(m => {
        if (m.parentId == item.id && !m.isPage) {
          if (!item.children) item.children = [];
          item.children.push(m);
        }
      })
      if (item.children) {
        buildMenusAndRouters(item.children);
      } else {
        layoutRouter.children.push({
          name: item.permissionPath,
          path: item.fullPath,
          component: _import(item.fullPath + "/index"),
          meta: {
            id: item.id,
            title: item.name,
            canMultipleOpen: item.canMultipleOpen
          }
        })
      }
    })
  }
  buildMenusAndRouters(menus);
  userStore.id = res.data.userId
  userStore.name = res.data.userName
  systemStore.permissionMenus = res.data.menuPermissions
  systemStore.menus = menus
  userStore.permissionMenus = res.data.menuPermissions
  userStore.menus = menus

  router.addRoute(layoutRouter)
  router.addRoute({ path: '/:catchAll(.*)', redirect: '/index' });
  return { path: to.path, replace: true }
})

router.afterEach((to, from) => {
  const systemStore = useSystemStore()
  const userStore = useUserStore()
  NProgress.done() // 结束Progress
  const title = systemStore.config.get('SYSTEM_TITLE')
  if (to.meta && to.meta.title) {
    document.title = to.meta.title + ' | ' + title
  } else {
    document.title = title
  }
})
export default router
